package online.longzipeng.householdbillssystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import online.longzipeng.householdbillssystem.business.entity.BillGroup;
import online.longzipeng.householdbillssystem.common.utils.ExceptionUtils;
import online.longzipeng.householdbillssystem.mapper.BillMapper;
import online.longzipeng.householdbillssystem.mapper.GroupMapper;
import online.longzipeng.householdbillssystem.service.BillGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lzp
 * @since 2021-04-17
 */
@Service
public class BillGroupServiceImpl extends ServiceImpl<BillGroupMapper, BillGroup> implements BillGroupService {

    @Autowired
    BillGroupMapper billGroupMapper;
    @Autowired
    GroupMapper groupMapper;
    @Autowired
    BillMapper billMapper;

    @Override
    public boolean add(BillGroup billGroup) {
        // 判断账单是否存在
        ExceptionUtils.isNotNull(billMapper.selectById(billGroup.getBillId()),"该账单不存在");
        // 判断用户组是否存在
        ExceptionUtils.isNotNull(groupMapper.selectById(billGroup.getGroupId()),"该用户组不存在");
        // 判断账单是否已经在该用户组中
        QueryWrapper<BillGroup> qwBillGroup = new QueryWrapper<>();
        qwBillGroup.eq("group_id",billGroup.getGroupId()).eq("bill_id",billGroup.getBillId());
        ExceptionUtils.isNull(billGroupMapper.selectList(qwBillGroup),"该账单已在该用户组中");
        return billGroupMapper.insert(billGroup) > 0;
    }

    @Override
    public boolean delete(Integer id) {
        try {
            billGroupMapper.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public BillGroup findById(Integer id) {
        return getById(id);
    }

    @Override
    public boolean edit(BillGroup billGroup) {
        return updateById(billGroup);
    }
}
